package com.shop.shopserver.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.shop.shopcommon.constant.RabbitMQConstant;
import com.shop.shopcommon.enumeration.PayStatusType;
import com.shop.shopcommon.utils.MultiDelayMessage;
import com.shop.shoppojo.dto.UpdateOrderDTO;
import com.shop.shoppojo.entity.UserOrder;
import com.shop.shopserver.mapper.OrderMapper;
import com.shop.shopserver.service.UpdateOrderStatusService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.UUID;

@Service
@Slf4j
public class ListenOrderDelayMessageHeader {
    @Autowired
    @Qualifier("rabbitComplexTemplate")
    private RabbitTemplate rabbitComplexTemplate;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UpdateOrderStatusService updateOrderStatusService;

    @RabbitListener(queues = RabbitMQConstant.DELAYED_QUEUE)
    public void listenOrderDelayMessage(String jsonString) throws JsonProcessingException {
        System.out.println("接送了");
        // 反序列化
        MultiDelayMessage message= objectMapper.readValue(jsonString, MultiDelayMessage.class);
        System.out.println("message:"+message);

        Object object = JSON.parse(message.getData());
        String userId = "";
        String orderId = "";
        if (object instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) object;
            orderId = jsonObject.getString("orderId");
            userId = jsonObject.getString("userId");
        }

        // 1. 查询订单状态
        UserOrder order = orderMapper.selectOne(new QueryWrapper<UserOrder>().eq("id", orderId));
        System.out.println("订单状态为"+order);
        // 2. 判断是否已经支付
        System.out.println(order.getPayStatus() +" "+ PayStatusType.PAY);
        if (order == null || Objects.equals(order.getPayStatus(), PayStatusType.PAY)) {
            System.out.println("订单不存在或者已经被处理");
            // 订单不存在或者已经被处理
            return;
        }

//        // TODO 3. 去支付服务查询真正的支付状态
//        boolean isPay = false;
//        // 3.1. 已支付，标记订单状态为已支付
//        if (isPay) {
//            orderService.markOrderPaySuccess(order.getId());
//            return;
//        }

        // 4. 判断是否存在延迟时间
        if (message.hasNextDelay()) {
            // 4.1. 存在，重发延迟消息
            Long nextDelay = message.removeNextDelay();
            System.out.println("准备发送");
            System.out.println("延迟为："+nextDelay.intValue());
            String jsonStringAgain = objectMapper.writeValueAsString(message);
            CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
            rabbitComplexTemplate.convertAndSend(
                    RabbitMQConstant.DELAYED_EXCHANGE,
                    RabbitMQConstant.ROUTING_KEY,
                    jsonStringAgain,
//                    new DelayMessageProcessor(nextDelay.intValue()));
                    msg -> {
                        msg.getMessageProperties().setHeader("x-delay", nextDelay.intValue()); // 设置延迟
                        return msg;
                    },
                    correlationData);
            return;
        }
        System.out.println("延时结束了,不存在，将取消订单");

        // 5. 不存在，取消订单
        log.info("将要取消的订单是"+orderId);
        LambdaQueryWrapper<UserOrder> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UserOrder::getId,orderId);
        UserOrder userOrder = orderMapper.selectOne(lqw);
        log.info("将要取消的订单的查询结果"+userOrder);

        if(userOrder == null ){
            log.info("暂无此订单");
            return;
        } else{
            // 异步取消订单
            updateOrderStatusService.asyncApplyCancelOrder(new UpdateOrderDTO(orderId), Long.parseLong(userId));
        }

        log.info("已取消订单");
    }


}

